package com.cf.utils.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.cf.utils.R;

public class myPaFilter extends AuthorizationFilter {
	private static final Logger log = LoggerFactory.getLogger(myPaFilter.class);

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		Boolean isPermission = false;
		Subject subject = getSubject(request, response);
		// 重写 不用角色 改用权限来判断
		String[] perms = (String[]) mappedValue;
		if (perms == null || perms.length == 0) {
			isPermission = true;
		} else {
			for (String perm : perms) {

				if (subject.isPermitted(perm)) {
					isPermission = true;
					break;
				}
			}
		}

		/*
		 * 替换成权限匹配，而不是角色 String[] roles = (String[]) mappedValue; if (roles ==
		 * null || roles.length == 0) { isPermission = true; } else { for
		 * (String role : roles) { log.info("role=" + role); if
		 * (subject.hasRole(role)) { isPermission = true; break; } } }
		 */

		return isPermission;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws IOException {

		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Content-Type",
				"application/json;charset=UTF-8");
		R r = R.error(444, "被系统无情拒绝了！");

		byte[] bytes = JSONObject.toJSONBytes(r);
		httpServletResponse.getOutputStream().write(bytes);
		return false;
	}
}
